﻿using System;
using nRoute.Components.Composition;
using Orktane.Components;
using Orktane.ScriptActionModel;

namespace Orktane.Sample.ConsoleApp.ScriptActions
{
    [MapScriptAction("GET-MEMINFO", "Memory Info", ShortDescription = "Provides current memory usage information.",
        Lifetime = InstanceLifetime.PerInstance)]
    public class GetMemInfoScriptAction 
        : IConsoleScriptAction
    {
        private const string MEM_INFO_FORMAT = "Current memory consumption is {0:###,###} (at {1:h:mm:ss tt}).";
        private const string GARBAGE_COLLECTED = "Garbage Collected.";
        private const string GARBAGE_COLLECT_OPTION = "GC";

        private IConsole _console;
        private IDisposable _completionToken;

#region IConsoleScriptAction Members

        public void Intialize(IConsole console, IDisposable completionToken)
        {
            if (console == null) throw new ArgumentNullException("console");
            if (completionToken == null) throw new ArgumentNullException("completionToken");

            _console = console;
            _completionToken = completionToken;
        }

        public bool Cancel()
        {
            return true;
        }

        public void Close() { }

#endregion

#region IScriptAction Members

        public void Execute(Arguments args)
        {
            // check if we need to do gc
            if (args != null && args.Exists(GARBAGE_COLLECT_OPTION)) DoGarbageCollect();
            WriteMemoryInfo();

            // signals end of the console
            _completionToken.Dispose();
        }

#endregion  

#region Helpers

        private void WriteMemoryInfo()
        {
            _console.WriteLine(MEM_INFO_FORMAT, GC.GetTotalMemory(false), DateTime.Now);
            _console.WriteLine();
        }

        private void DoGarbageCollect()
        {
            GC.Collect();
            GC.Collect();
            _console.WriteLine(GARBAGE_COLLECTED);
        }

#endregion

    }
}
